from hashlib import sha1
import math
import os

from BitClient.torrent import Torrent
from BitClient.client import Block, Piece

fd = os.open('/home/omnisky/APP/myBitClient/debian-12.1.0-amd64-netinst.iso', os.O_RDONLY)

torrent = Torrent('./tests/debian-12.1.0-amd64-netinst.iso.torrent')


col = 100
items = len(torrent.pieces)
row = items // col



import tkinter as tk
# from tkinter import ttk

top = tk.Tk()
gui_piece = []

w = tk.Canvas(top, width = 707, height =8 + 5 + (5 + 2) * row )
w.pack()


r = 0
c = 0
while items:
    x = 5 + (5 + 2) * c
    y = 5 + (5 + 2) * r
    w.create_rectangle(x, y, x + 5, y + 5, fill = "lightgrey")

    items -= 1
    c += 1
    if c >= col:
        c = 0
        r += 1

# for r in range(row):
#     for c in range(col):
#         btn = tk.Checkbutton(top, width=0, onvalue = 1, offvalue = 0,)
#         btn.grid(row=r, column=c)
#         gui_piece.append(btn)

# r = row
# c = 0
# while extra:
#     btn = tk.Checkbutton(top, width=0, onvalue = 1, offvalue = 0,)
#     btn.grid(row=r, column=c)
#     gui_piece.append(btn)
#     extra -= 1
#     c += 1
#     if c > col:
#         c = 0
#         r += 1

# C1 = Checkbutton(top, onvalue = 1, offvalue = 0,)
# C2 = Checkbutton(top, onvalue = 1, offvalue = 0,)
# C1.grid()
# C2.grid()


def index_2_row_col(index: int):
    row = index // 100
    col = index % 100
    return row, col

have_pieces = []
missing_pieces = []

for index, piece in enumerate(torrent.pieces):
    piece_in = os.read(fd, torrent.piece_length)

    if sha1(piece_in).digest() == piece:
        # print('ok')
        have_pieces.append(piece)
        # gui_piece[index].select()
        r, c = index_2_row_col(index)
        x = 5 + (5 + 2) * c
        y = 5 + (5 + 2) * r
        w.create_rectangle(x, y, x + 5, y + 5, fill = "green")
    else:
        missing_pieces.append(piece)

print(len(have_pieces))
print(len(missing_pieces))


top.mainloop()


print(1)